﻿Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text.RegularExpressions


Namespace DotNetNuke.Modules.ActiveForums.Controls
    <DefaultProperty("Text"), ToolboxData("<{0}:UserProfile runat=server></{0}:UserProfile>")> _
    Public Class UserProfile
        Inherits ProfileBase
#Region "Enum"
        Enum ProfileModes
            View
            Edit
        End Enum
#End Region
#Region "Private Members"
        Private _profileMode As ProfileModes = ProfileModes.View
#End Region
#Region "Public Properties"
        Public Property ProfileMode() As ProfileModes
            Get
                Return _profileMode
            End Get
            Set(ByVal value As ProfileModes)
                _profileMode = value
            End Set
        End Property
#End Region
#Region "Protected Members"
        Protected WithEvents plh As New PlaceHolder
        Protected WithEvents plhTabs As New PlaceHolder
        Protected WithEvents plhProfileAdminSettings As New PlaceHolder
        Protected WithEvents plhProfilePrefs As New PlaceHolder
        Protected WithEvents plhProfileUserAccount As New PlaceHolder
        Protected WithEvents plhTracker As New PlaceHolder
        Protected WithEvents plhProfileEditButton As New PlaceHolder
        Protected WithEvents plhProfileSaveButton As New PlaceHolder
        Protected WithEvents plhProfileCancelButton As New PlaceHolder
        Protected WithEvents amTabs As New DotNetNuke.Modules.ActiveForums.Controls.ActiveTabs
        'Edit Mode
        Protected WithEvents txtWebSite As Global.System.Web.UI.WebControls.TextBox
        Protected WithEvents txtOccupation As Global.System.Web.UI.WebControls.TextBox
        Protected WithEvents txtLocation As Global.System.Web.UI.WebControls.TextBox
        Protected WithEvents txtInterests As Global.System.Web.UI.WebControls.TextBox
        
        Protected WithEvents txtYahoo As Global.System.Web.UI.WebControls.TextBox
        Protected WithEvents txtMSN As Global.System.Web.UI.WebControls.TextBox
        Protected WithEvents txtICQ As Global.System.Web.UI.WebControls.TextBox
        Protected WithEvents txtAOL As Global.System.Web.UI.WebControls.TextBox
        Protected WithEvents txtSignature As Global.System.Web.UI.WebControls.TextBox
        Protected WithEvents btnProfileEdit As Global.DotNetNuke.Modules.ActiveForums.Controls.ImageButton
        Protected WithEvents btnProfileSave As Global.DotNetNuke.Modules.ActiveForums.Controls.ImageButton
        Protected WithEvents btnProfileCancel As Global.DotNetNuke.Modules.ActiveForums.Controls.ImageButton
        Protected WithEvents trAvatarLinks As Global.System.Web.UI.HtmlControls.HtmlTableRow
        Protected WithEvents tblAvatars As Global.System.Web.UI.HtmlControls.HtmlTable
        Protected WithEvents lblAvatarError As Global.System.Web.UI.WebControls.Label

#End Region
#Region "Event Handlers"

        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            Me.AppRelativeVirtualPath = "~/"
            Try
                If Not Request.QueryString("mode") Is Nothing Then
                    If Request.QueryString("mode").ToLowerInvariant = "edit" And CanEditMode() Then
                        ProfileMode = ProfileModes.Edit
                    Else
                        GoViewURL()
                    End If
                Else
                    ProfileMode = ProfileModes.View
                End If
            Catch ex As Exception
                ProfileMode = ProfileModes.View
            End Try
            
        End Sub
        Private Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim sTemplate As String = String.Empty
            If IO.File.Exists(Server.MapPath(ImagePath & "/_userprofile.txt")) Then
                sTemplate = Utilities.GetFileContent(Server.MapPath(ImagePath & "/_userprofile.txt"))
            Else
                sTemplate = Utilities.GetFileContent(Server.MapPath("~/DesktopModules/ActiveForums/config/templates/_userprofile.txt"))
            End If
            sTemplate = Utilities.ParseSpacer(sTemplate)
#If SKU <> "LITE" Then
            If MainSettings.ProfileType = ProfileTypes.Social Then
                If Not sTemplate.Contains(Globals.SocialRegisterTag) Then
                    sTemplate = Globals.SocialRegisterTag & sTemplate
                End If
            End If
#End If
            If ProfileMode = ProfileModes.Edit Then
                sTemplate = "<%@ Register TagPrefix=""dnn"" Assembly=""DotNetNuke"" Namespace=""DotNetNuke.UI.WebControls""%>" & sTemplate
            End If
            Dim lit As New Literal
            Dim upc As New UserController
            Dim up As User = upc.GetUser(PortalId, ModuleId, UID)
            Dim fc As New ForumController
            up.UserForums = fc.GetForumsForUser(up.UserRoles, PortalId, ForumModuleId, "CanRead")
            sTemplate = TemplateUtils.ParseProfileTemplate(sTemplate, up, PortalId, ModuleId, ImagePath, CurrentUserType, ProfileMode, UserInfo.UserID, TimeZoneOffset)
            sTemplate = RenderModals(sTemplate)

            sTemplate = sTemplate.Replace("[AM:CONTROLS:AdminProfileSettings]", "<asp:placeholder id=""plhProfileAdminSettings"" runat=""server"" />")
            sTemplate = sTemplate.Replace("[AM:CONTROLS:ProfileMyPreferences]", "<asp:placeholder id=""plhProfilePrefs"" runat=""server"" />")
            sTemplate = sTemplate.Replace("[AM:CONTROLS:ProfileUserAccount]", "<asp:placeholder id=""plhProfileUserAccount"" runat=""server"" />")
            sTemplate = sTemplate.Replace("[AM:CONTROLS:ProfileForumTracker]", "<asp:placeholder id=""plhTracker"" runat=""server"" />")
            sTemplate = sTemplate.Replace("[AF:PROFILE:VIEWUSERPOSTS]", "<a href=""" & NavigateUrl(TabId, "", ParamKeys.ViewType & "=search&uid=" & UID.ToString) & """>[RESX:ViewPostsByUser]</a>")



            sTemplate = GetTabsSection(sTemplate)
            Dim ctl As Control = Me.ParseControl(sTemplate)
            Me.Controls.Add(ctl)
            While Not ctl.Controls.Count = 0
                Me.Controls.Add(ctl.Controls.Item(0))
            End While
            'Begin Load Tab Control
            plhTabs = CType(Me.FindControl("plhTabs"), PlaceHolder)
            If Not plhTabs Is Nothing And Not amTabs Is Nothing Then
                plhTabs.Controls.Add(amTabs)
            End If
            LinkControls(Controls)
            If Not plhProfileEditButton Is Nothing Then
                btnProfileEdit = New ImageButton
                With btnProfileEdit
                    .ID = "btnProfileEdit"
                    .CssClass = "amimagebutton"
                    .PostBack = True
                    .Height = 50
                    .Width = 50
                    .ImageLocation = "TOP"
                    .Text = "[RESX:Button:Edit]"
                    .ImageUrl = "~/DesktopModules/ActiveForums/images/edit32.png"
                    .Visible = False
                End With
                plhProfileEditButton.Controls.Add(btnProfileEdit)
            End If
            If Not plhProfileCancelButton Is Nothing Then
                btnProfileCancel = New ImageButton
                With btnProfileCancel
                    .ID = "btnProfileCancel"
                    .CssClass = "amimagebutton"
                    .PostBack = True
                    .Height = 50
                    .Width = 50
                    .ImageLocation = "TOP"
                    .Text = "[RESX:Button:Cancel]"
                    .ImageUrl = "~/DesktopModules/ActiveForums/images/cancel32.png"
                    .Visible = False
                End With
                plhProfileCancelButton.Controls.Add(btnProfileCancel)
            End If
            If Not plhProfileSaveButton Is Nothing Then
                btnProfileSave = New ImageButton
                With btnProfileSave
                    .ID = "btnProfileSave"
                    .CssClass = "amimagebutton"
                    .PostBack = True
                    .Height = 50
                    .Width = 50
                    .ImageLocation = "TOP"
                    .Text = "[RESX:Button:Save]"
                    .ImageUrl = "~/DesktopModules/ActiveForums/images/save32.png"
                    .Visible = False
                End With
                plhProfileSaveButton.Controls.Add(btnProfileSave)
            End If

            If Not plhProfileAdminSettings Is Nothing Then
                Dim tmpCtl As ProfileBase = CType(Me.LoadControl("~/DesktopModules/ActiveForums/controls/profile_adminsettings.ascx"), ProfileBase)
                tmpCtl.ModuleConfiguration = Me.ModuleConfiguration
                tmpCtl.UserProfile = up.Profile
                plhProfileAdminSettings.Controls.Add(tmpCtl)
            End If
            If Not plhProfilePrefs Is Nothing Then
                Dim tmpCtl As ProfileBase = CType(Me.LoadControl("~/DesktopModules/ActiveForums/controls/profile_mypreferences.ascx"), ProfileBase)
                tmpCtl.ModuleConfiguration = Me.ModuleConfiguration
                tmpCtl.UserProfile = up.Profile
                plhProfilePrefs.Controls.Add(tmpCtl)
            End If
            If Not plhProfileUserAccount Is Nothing Then
                Dim tmpCtl As ProfileBase = CType(Me.LoadControl("~/DesktopModules/ActiveForums/controls/profile_useraccount.ascx"), ProfileBase)
                tmpCtl.ModuleConfiguration = Me.ModuleConfiguration
                tmpCtl.UserProfile = up.Profile
                plhProfileUserAccount.Controls.Add(tmpCtl)
            End If
            If Not plhTracker Is Nothing Then
                Dim ctlForums As New ForumView
                ctlForums.ModuleConfiguration = Me.ModuleConfiguration
                ctlForums.DisplayTemplate = DataCache.GetTemplate("ForumTracking.txt")
                ctlForums.CurrentUserId = UID
                ctlForums.ForumIds = up.UserForums
                plhTracker.Controls.Add(ctlForums)
            End If
            If Not btnProfileEdit Is Nothing Then
                If Not CurrentUserType = CurrentUserTypes.Anon And (UID = Me.UserId Or (CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.SuperUser)) Then
                    If ProfileMode = ProfileModes.View Then
                        btnProfileEdit.Visible = True
                        btnProfileCancel.Visible = False
                        btnProfileSave.Visible = False
                    Else
                        btnProfileEdit.Visible = False
                        btnProfileCancel.Visible = True
                        btnProfileSave.Visible = True
                    End If
                End If
            End If

        End Sub

        Private Sub btnProfileEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProfileEdit.Click
            If Not CurrentUserType = CurrentUserTypes.Anon And (UID = Me.UserId Or (CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.SuperUser)) Then
                Response.Redirect(NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=profile", "uid=" & UID, "mode=edit"}))
            End If
        End Sub
        Private Sub btnProfileCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProfileCancel.Click
            GoViewURL()
        End Sub
        Private Sub btnProfileSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProfileSave.Click
            If SaveProfile() Then
                GoViewURL()
            End If
        End Sub
#End Region
#Region "Private Methods"
        Private Sub GoViewURL()
            Response.Redirect(NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=profile", "uid=" & UID}))
        End Sub
        Private Function CanEditMode() As Boolean
            If Not CurrentUserType = CurrentUserTypes.Anon And (UID = Me.UserId Or (CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.SuperUser)) Then
                Return True
            Else
                Return False
            End If
        End Function
        Private Sub LinkControls(ByVal ctrls As ControlCollection)
            For Each ctrl As Control In ctrls
                Select Case ctrl.ID
                    Case "plhProfileAdminSettings"
                        plhProfileAdminSettings = CType(ctrl, PlaceHolder)
                    Case "plhProfilePrefs"
                        plhProfilePrefs = CType(ctrl, PlaceHolder)
                    Case "plhProfileUserAccount"
                        plhProfileUserAccount = CType(ctrl, PlaceHolder)
                    Case "plhTracker"
                        plhTracker = CType(ctrl, PlaceHolder)
                    Case "plhProfileEditButton"
                        plhProfileEditButton = CType(ctrl, PlaceHolder)
                    Case "plhProfileSaveButton"
                        plhProfileSaveButton = CType(ctrl, PlaceHolder)
                    Case "plhProfileCancelButton"
                        plhProfileCancelButton = CType(ctrl, PlaceHolder)
                    Case "txtWebSite"
                        txtWebSite = CType(ctrl, TextBox)
                    Case "txtOccupation"
                        txtOccupation = CType(ctrl, TextBox)
                    Case "txtLocation"
                        txtLocation = CType(ctrl, TextBox)
                    Case "txtInterests"
                        txtInterests = CType(ctrl, TextBox)
                   
                    Case "trAvatarLinks"
                        trAvatarLinks = CType(ctrl, System.Web.UI.HtmlControls.HtmlTableRow)
                    Case "tblAvatars"
                        tblAvatars = CType(ctrl, System.Web.UI.HtmlControls.HtmlTable)
                    Case "txtYahoo"
                        txtYahoo = CType(ctrl, TextBox)
                    Case "txtMSN"
                        txtMSN = CType(ctrl, TextBox)
                    Case "txtICQ"
                        txtICQ = CType(ctrl, TextBox)
                    Case "txtAOL"
                        txtAOL = CType(ctrl, TextBox)
                    Case "txtSignature"
                        txtSignature = CType(ctrl, TextBox)
                    Case "btnProfileEdit"
                        btnProfileEdit = CType(ctrl, ImageButton)
                    Case "btnProfileCancel"
                        btnProfileCancel = CType(ctrl, ImageButton)
                    Case "btnProfileSave"
                        btnProfileSave = CType(ctrl, ImageButton)
                    Case "lblAvatarError"
                        lblAvatarError = CType(ctrl, Label)
                End Select
                If ctrl.Controls.Count > 0 Then
                    LinkControls(ctrl.Controls)
                End If
            Next
        End Sub
        Private Function SaveProfile() As Boolean
            If CanEditMode() Then
                Dim objuser As DotNetNuke.Entities.Users.UserInfo = DotNetNuke.Entities.Users.UserController.GetUser(PortalId, UID, True)
                Dim upc As New UserProfileController
                Dim uc As New UserController
                Dim upi As UserProfileInfo = uc.GetUser(PortalId, ModuleId, UID).Profile
                If Not upi Is Nothing Then
                    With upi
                        .WebSite = Utilities.XSSFilter(txtWebSite.Text, True)
                        .Occupation = Utilities.XSSFilter(txtOccupation.Text, True)
                        .Location = Utilities.XSSFilter(txtLocation.Text, True)
                        .Interests = Utilities.XSSFilter(txtInterests.Text, True)
                        .Yahoo = Utilities.XSSFilter(txtYahoo.Text, True)
                        .MSN = Utilities.XSSFilter(txtMSN.Text, True)
                        .ICQ = Utilities.XSSFilter(txtICQ.Text, True)
                        .AOL = Utilities.XSSFilter(txtAOL.Text, True)
                        If MainSettings.AllowSignatures = 1 Then
                            .Signature = Utilities.XSSFilter(txtSignature.Text, True)
                            .Signature = Utilities.StripHTMLTag(.Signature)
                            .Signature = Utilities.HTMLEncode(.Signature)
                        ElseIf MainSettings.AllowSignatures = 2 Then
                            .Signature = Utilities.XSSFilter(txtSignature.Text, False)
                        End If
                       


                    End With
                    upc.Profiles_Save(upi)
                    Dim blnSaveProfile As Boolean = False

                    Dim profprop As New DotNetNuke.Entities.Profile.ProfilePropertyDefinition()
                    Dim profproperties As New DotNetNuke.Entities.Profile.ProfilePropertyDefinitionCollection()
                    profproperties = objuser.Profile.ProfileProperties()
                    For Each profprop In profproperties
                        Dim ctl As Control = RecursiveFind(Me, "dnnctl" & profprop.PropertyName)
                        If Not ctl Is Nothing Then
                            If TypeOf ctl Is TextBox Then
                                Dim txt As TextBox = CType(ctl, TextBox)
                                If txt.ID.Contains("dnnctl") Then
                                    blnSaveProfile = True
                                    Dim propName As String = txt.ID.Replace("dnnctl", String.Empty)
                                    objuser.Profile.GetProperty(propName).PropertyValue = txt.Text
                                End If

                            End If
                        End If
                    Next

                    If blnSaveProfile Then
                        DotNetNuke.Entities.Users.UserController.UpdateUser(PortalId, objuser)
                    End If
                End If
            End If
            Return True
        End Function
        Private Function RecursiveFind(ByVal ctl As Control, ByVal controlId As String) As Control
            If ctl.ID = controlId Then
                Return ctl
            End If
            For Each tmpctl As Control In ctl.Controls
                Dim t As Control = RecursiveFind(tmpctl, controlId)
                If Not t Is Nothing Then
                    Return t
                End If
            Next
            Return Nothing
        End Function
        

        Private Function RenderModals(ByVal Template As String) As String
            Dim sOut As String = Template
            '[AM:CONTROLS:MODAL:MyPreferences:Private]
            Dim pattern As String = "(\[AM:CONTROLS:MODAL:(.+?)\])"
            Dim regExp As New Regex(pattern)
            Dim matches As MatchCollection
            matches = regExp.Matches(sOut)
            Dim bAddModal As Boolean = False
            For Each match As Match In matches
                Dim matchValue As String = match.Groups(2).Value
                If matchValue.Contains(":") Then
                    Dim sec As String = matchValue.Split(CChar(":"))(1).ToLowerInvariant
                    Select Case sec.ToLowerInvariant
                        Case "anon"
                            bAddModal = True
                        Case "private"
                            If Not CurrentUserType = CurrentUserTypes.Anon Then
                                If UserId = UID Or (CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.SuperUser) Then
                                    bAddModal = True
                                End If
                            End If
                        Case "auth"
                            If Not CurrentUserType = CurrentUserTypes.Anon Then
                                bAddModal = True
                            End If
                        Case "forummod"
                            If Not CurrentUserType = CurrentUserTypes.Anon And Not CurrentUserType = CurrentUserTypes.Auth Then
                                bAddModal = True
                            End If
                        Case "admin"
                            If CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.SuperUser Then
                                bAddModal = True
                            End If
                        Case "superuser"
                            If CurrentUserType = CurrentUserTypes.SuperUser Then
                                bAddModal = True
                            End If
                        Case Else
                            bAddModal = UserInfo.IsInRole(sec)
                    End Select
                    matchValue = matchValue.Split(CChar(":"))(0)
                Else
                    bAddModal = True
                End If
                If bAddModal = True Then
                    Dim sModalDivId As String = "afmodal" & matchValue
                    Dim sModalText As String = "[RESX:Label:" & matchValue & "]"
                    Dim sModalContent As String = String.Empty
                    Template = Template.Replace(match.Value, "<a href=""javascript:void(0);"" onclick=""amOpenModal('" & sModalDivId & "','" & sModalText & "',350, 300);"">" & sModalText & "</a>" & match.Value)
                    If sOut.Contains(match.Value.Replace("[AM", "[/AM")) Then
                        Dim tmp As String = TemplateUtils.GetTemplateSection(sOut, match.Value, match.Value.Replace("[AM", "[/AM"))
                        sModalContent = "<div id=""" & sModalDivId & """ style=""display:none;"">" & tmp & "</div>"
                    End If
                    Template = TemplateUtils.ReplaceSubSection(Template, String.Empty, match.Value, match.Value.Replace("[AM", "[/AM"))
                    Template = Template & sModalContent
                End If

            Next match
            Return Template
        End Function

        Private Function GetTabsSection(ByVal Template As String) As String
            Dim sOut As String = String.Empty
            sOut = TemplateUtils.GetTemplateSection(Template, "[AM:CONTROLS:TABS]", "[/AM:CONTROLS:TABS]")
            Dim pattern As String = "(\[AM:CONTROLS:TAB:(.+?)\])"
            Dim regExp As New Regex(pattern)
            Dim matches As MatchCollection
            matches = regExp.Matches(sOut)
            amTabs = New DotNetNuke.Modules.ActiveForums.Controls.ActiveTabs
            For Each match As Match In matches
                Dim bAddTab As Boolean = False
                Dim matchValue As String = match.Groups(2).Value
                Dim access As CurrentUserTypes = CurrentUserTypes.Anon
                If matchValue.Contains(":") Then
                    Dim sec As String = matchValue.Split(CChar(":"))(1).ToLowerInvariant
                    If sec = "private" Then
                        If Not CurrentUserType = CurrentUserTypes.Anon Then
                            If UserId = UID Or (CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.SuperUser) Then
                                bAddTab = True
                                access = CurrentUserTypes.Admin
                            End If
                        End If
                    Else
                        Select Case sec
                            Case "auth"
                                access = CurrentUserTypes.Auth
                            Case "forummod"
                                access = CurrentUserTypes.ForumMod
                            Case "admin"
                                access = CurrentUserTypes.Admin
                            Case "superuser"
                                access = CurrentUserTypes.SuperUser
                        End Select
                        Select Case access
                            Case CurrentUserTypes.Anon
                                bAddTab = True
                            Case CurrentUserTypes.Auth
                                If Not CurrentUserType = CurrentUserTypes.Anon Then
                                    bAddTab = True
                                End If
                            Case CurrentUserTypes.ForumMod
                                If Not CurrentUserType = CurrentUserTypes.Anon And Not CurrentUserType = CurrentUserTypes.Auth Then
                                    bAddTab = True
                                End If
                            Case CurrentUserTypes.Admin
                                If CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.SuperUser Then
                                    bAddTab = True
                                End If
                            Case CurrentUserTypes.SuperUser
                                If CurrentUserType = CurrentUserTypes.SuperUser Then
                                    bAddTab = True
                                End If
                        End Select
                    End If
                    matchValue = matchValue.Split(CChar(":"))(0)
                Else
                    bAddTab = True
                End If


                If bAddTab Then
                    Dim tb As New DotNetNuke.Modules.ActiveForums.Controls.Tab
                    tb.ControlKey = matchValue
                    tb.Text = "[RESX:Label:" & matchValue & "]"
                    If sOut.Contains(match.Value.Replace("[AM", "[/AM")) Then
                        Dim tbc As New DotNetNuke.Modules.ActiveForums.Controls.TabContent
                        Dim tmp As String = TemplateUtils.GetTemplateSection(sOut, match.Value, match.Value.Replace("[AM", "[/AM"))
                        If tmp.Contains("<dnn:") Then
                            tmp = "<%@ Register TagPrefix=""dnn"" Assembly=""DotNetNuke"" Namespace=""DotNetNuke.UI.WebControls""%>" & tmp
                        End If
                        If tmp.Contains("<social:") Then
                            tmp = Globals.SocialRegisterTag & tmp
                        End If
                        Dim ctl As Control = Me.ParseControl(tmp)
                        tbc.Controls.Add(ctl)
                        tb.Content = tbc
                    End If
                    amTabs.Tabs.Add(tb)
                End If

            Next match
            Template = TemplateUtils.ReplaceSubSection(Template, "<asp:placeholder id=""plhTabs"" runat=""server"" />", "[AM:CONTROLS:TABS]", "[/AM:CONTROLS:TABS]")
            Return Template
        End Function
#End Region


        
        
    End Class
End Namespace